/**
 * 
 */
package com.iptv;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.base.Operation;
import com.base.Target;
import com.base.User;
import com.common.enumeration.OperationTypeEnum;
import com.iptv.enumeration.TargetTypeEnum;
import com.iptv.operation.IptvUserOperation;
import com.iptv.operation.ProgramOperation;
import com.iptv.target.Program;

/**
 * @author 4833 robben
 * 2014-5-10 下午4:47:47
 */
public class IptvUser extends User {
	// inject thes objects by spring !
	private ProgramOperation programOperation = new ProgramOperation();
	private IptvUserOperation iptvUserOperation = new IptvUserOperation();
	
	public IptvUser login() {
		if (LoginUserManager.isOnline(this.getCode())) {
			return LoginUserManager.find(this.getCode());
		} else {
			// TODO: find user from database.
			IptvUser user = iptvUserOperation.findByNameAndPassword(this.getName(), this.getPassword());
			// remember user when login.
			LoginUserManager.remember(user.getCode());
			
			return user;
		}
		
	}
	
	public boolean logout(User user) {
		// forget user when logout.
		LoginUserManager.forget(user.getCode());
		return true;
	}
	
	public String addProgram(Program program) {
		iptvUserOperation.setType(OperationTypeEnum.ADD.name());
		return this.doAddOperation(programOperation, program);
	}
	
	public List<Program> getProgramList() {
		iptvUserOperation.setType(OperationTypeEnum.RETRIEVE.name());
		return this.doGetListOperation(programOperation, TargetTypeEnum.PROGRAM.name());
	}
	
	public String addIptvUser(IptvUser iptvUser) {
		iptvUserOperation.setType(OperationTypeEnum.ADD.name());
		return this.doAddOperation(iptvUserOperation, iptvUser);
	}
	
	public List<Program> doGetListOperation(Operation operation, String targetTypeCode) {
		if(operation.checkRight(this.getUserGroup().getCode(), targetTypeCode)) {
			
			Map<String, String> parameters = new HashMap<String, String>();
			parameters .put("usergroupCode", this.getUserGroup().getCode());
			parameters.put("operationCode", this.getCode());
			parameters.put("targetTypeCode", targetTypeCode);
			
			return operation.find(parameters);
		} else {
			return null;
		}
	}
}
